import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom";
import "./App.less";
import Login from "./views/login";
import Updating from "./views/updating";
import Discover from "./views/discover";
import DiscoverList from "./views/discover/list";
import TerritoryModify from "./views/territory/modify";
import TerritoryList from "./views/territory/list";
import Myfiles from "./views/myfiles";
import Reward from "./views/reward";
import Account from "./views/account";
import FileDetail from "./views/file-detail";
import TestSign from "./views/test/sign";
import { CloseOutlined, PauseOutlined, CaretRightOutlined } from "@ant-design/icons";


import store from "./utils/store";
import { loading, alert, noti, notiOK } from "./utils/antd-helper";
import * as suture from "./services/suture";
import * as oss from "./services/oss";
import * as evm from "./services/evm";
import { getFileTypeId } from "./utils/file-helper";
import { checkLogin } from "./services/user";
import * as antdHelper from "./utils/antd-helper";
import webconfig from "./webconfig";

import React, { useState, useEffect } from "react";
import { Popconfirm, Empty, Modal, Progress, Button } from "antd";
let lastPath = "";
let isFirst = true;
let timeout = null;
let timeout2 = null;
let isLeave = false;
window.isAuthor = true;
window.myTerritories = [];

function App() {
	const navigate = useNavigate();
	const [uploadBoxTab, setUploadBoxTab] = useState("uploading");
	const [isloading, setIsloading] = useState(false);
	const [account, setAccount] = useState();
	const [keyword, setKeyword] = useState("");
	const [isAuth, setIsAuth] = useState(true);
	const [current, setCurrent] = useState("");
	const [showFileListBox, setShowFileListBox] = useState(false);
	const [territoryInfo, setTerritoryInfo] = useState();

	const [uploadingFiles, setUploadingFiles] = useState([]);
	const [transferredFiles, setTransferredFiles] = useState([]);

	const [isUploading, setIsUploading] = useState(false);


	const onClick = async e => {
		if (e != "discover" && !store.get("token")) {
			// antdHelper.msgError("Go to login");
			navigate("/login");
			return;
		}
		setCurrent(e);
		navigate(e);
	};
	const queryMyTerritorys = async () => {
		let acc = oss.getAccount();
		setAccount(acc);
		let ret = await suture.territories();
		if (ret.msg != 'ok' || !ret.data || ret.data.length < 1) {
			setTerritoryInfo();
			return ret;
		}
		window.myTerritories = ret.data;
		setTerritoryInfo(ret.data[0]);
		console.log(ret.data[0]);
		return ret;
	}
	const init = async () => {
		isLeave = false;
		await oss.init();
		let acc = oss.getAccount();
		if (!acc) {
			setAccount(null);
			console.log("unlogin,try after 3s");
			setTimeout(init, 3000);
			return;
		}
		setAccount(acc);
		await oss.queryBalance();
		acc = oss.getAccount();
		setAccount(acc);
		let isAuthor = true;
		isAuthor = await oss.checkAuthority();
		console.log({ isAuthor });
		if (!isAuthor && acc && window.location.href.indexOf("login") == -1) {
			await suture.authorize();
			isAuthor = await oss.checkAuthority();
		}
		setIsAuth(isAuthor);
		window.isAuthor = isAuthor;
		acc = oss.getAccount();
		let token = store.get("token");
		if (token) {
			suture.territoryRefresh(true);
		}
		return acc;
	};
	useEffect(() => {
		init();
		queryMyTerritorys();
		window.refreshSpace = queryMyTerritorys;
		window.setShowFileListBox = setShowFileListBox;
		filterUploadStateList();
		window.refreshUploadingFiles = () => {
			console.log("call refreshUploadingFiles");
			if (isLeave) return;
			let n = window.uploadingList;
			n = n.slice(0);
			setUploadingFiles(n);
			let tmp = n.find(t => t.state == "pending" || t.state == "waiting");
			setIsUploading(tmp ? true : false);
			filterUploadStateList();
			// console.log({ uploadingFiles, n });
			if (isFirst) {
				isFirst = false;
			}
		};
	}, []);
	useEffect(() => {
		timeout = setInterval(function () {
			if (isLeave) return;
			let p = window.location.pathname;
			p = p.replace("/", "");
			if (p == lastPath) return;
			// console.log("pathname", p, current);
			if (p == "") p = "discover";
			lastPath = p;
			setCurrent(p);
		}, 500);
		return () => {
			clearInterval(timeout);
			isLeave = true;
		};
	}, []);

	const onUploadTabTurn = (n) => {
		setUploadBoxTab(n);
		filterUploadStateList();
	};
	const filterUploadStateList = () => {
		let uploading = [], transferred = [];
		window.uploadingList.forEach(t => {
			let isUploading = t.state == 'waiting' || t.state == 'pending' || t.state == 'pause';
			if (isUploading) {
				uploading.push(t);
			} else {
				transferred.push(t);
			}
		});
		setUploadingFiles(uploading);
		setTransferredFiles(transferred);
	};
	const onAuthorize = async () => {
		setIsloading(true);
		loading("Loading...");
		await suture.authorize(true);
		let isAuthor = await oss.checkAuthority();
		setIsAuth(isAuthor);
		setIsloading(false);
		window.isAuthor = isAuthor;
		loading();
	};
	const onInput = (e, n) => {
		let v = e.target.value;
		setKeyword(v.trim());
	};
	const onSearch = () => {
		if (!keyword) {
			return;
		}
		let url = "/detail/" + keyword;
		if (window.location.href.includes("/detail/")) {
			window.location.href = url;
			return;
		}
		// navigate('/myfiles/'+keyword);
		// alert('File not found');
		navigate(url);
		setKeyword("");
	};
	const onCancelUpload = async item => {
		let isUploading = item.state == 'waiting' || item.state == 'pending' || item.state == 'pause';
		if (isUploading) {
			let yes = await antdHelper.confirm("Are you sure cancel the upload?");
			if (!yes) return;
		}
		if (item.stop && typeof item.stop == "function") {
			item.stop();
		}
		onRemoveUpload(item);
	};
	const onRemoveUpload = async item => {
		let i = window.uploadingList.findIndex(t => t.id == item.id);
		if (i > -1) {
			window.uploadingList.splice(i, 1);
		}
		window.refreshUploadingFiles();
	};
	const onPauseUpload = async item => {
		if (!item.pause || typeof item.pause != "function") {
			return console.log('not a pause function');
		}
		console.log('pausing');
		item.pause();
	};
	const onResumeUpload = async item => {
		if (!item.resume || typeof item.resume != "function") {
			return;
		}
		item.resume();
	};
	const rendUploadList = (t, i) => {
		return (
			<div className="file-item" key={t.name + i}>
				<div className="line1">
					<div className="left">
						<img src={process.env.PUBLIC_URL + "/img/filetype/" + getFileTypeId(t.name) + ".png"} />
						<div>
							<span className="t1">{t.name}</span>
							<span className="t2">{t.sizeStr}</span>
						</div>
					</div>
					<div className="right">
						{t.state == "pending" ? (
							<span className="t6" onClick={() => onPauseUpload(t)} title="pause upload">
								<PauseOutlined style={{ fontSize: 18, color: "green", cursor: "pointer" }} />
							</span>
						) : t.state == "pause" ? (
							<span className="t6" onClick={() => onResumeUpload(t)} title="resume upload">
								<CaretRightOutlined style={{ fontSize: 18, color: "green", cursor: "pointer" }} />

							</span>
						) : ""}
						<span className="t6" onClick={() => onCancelUpload(t)}>
							<CloseOutlined style={{ fontSize: 18, color: "red", cursor: "pointer" }} />
						</span>
					</div>
				</div>
				<div className="line2">
					<Progress percent={t.per} size="small" />
				</div>
				<div className="line3">
					<span className="t4">{t.per}%</span>
					<span className="t5">{t.state == "pending" ? t.speed : t.state}</span>
				</div>
			</div>
		);
	}
	const onShowUploadbox = () => {
		let acc = oss.getAccount();
		if (!acc) {
			return navigate("/login");
		}
		setShowFileListBox(true);
	}
	if (webconfig.isUpdating) return <Updating />;


	return (
		<div className="App">
			{window.location.href.indexOf("login") != -1 ? (
				<Login />
			) : window.location.href.indexOf("sign") != -1 ? (
				<TestSign />
			) : (
				<div className="containner2">
					<div className="top-side">
						<div className="logo-box">
							<img width={130} src={process.env.PUBLIC_URL + "/img/logo.png"} />
						</div>
						<div className="search-box">
							<div className="search-con">
								<img className="cess-logo" width={20} src={process.env.PUBLIC_URL + "/img/icon_cess.png"} />
								<span className="cess-txt">CESS</span>
								<input type="text" value={keyword} onChange={onInput} onKeyUp={onInput} onInput={onInput} placeholder="Search file by Fid" />
								<div className="search-btn" onClick={onSearch}>
									<img className="search-icon" width={20} src={process.env.PUBLIC_URL + "/img/search.png"} />
								</div>
							</div>
						</div>
					</div>
					<div className="left-side">
						<div className="nav-box">
							<div
								onClick={() => onClick("discover")}
								className={current == "discover" ? "curr discover" : "discover"}
								style={{ backgroundImage: "url(" + process.env.PUBLIC_URL + "/img/menu-1.png)" }}>
								Discover
							</div>
							<div
								onClick={() => onClick("myfiles")}
								className={current == "myfiles" ? "curr myfiles" : "myfiles"}
								style={{ backgroundImage: "url(" + process.env.PUBLIC_URL + "/img/menu-2.png)" }}>
								My Files
							</div>
							<div
								onClick={onShowUploadbox}
								className={current == "reward" ? "curr reward" : "reward"}
								style={{ backgroundImage: "url(" + process.env.PUBLIC_URL + "/img/menu-3.png)" }}>
								{/* <i className={isUploading ? "bg-icon rotate" : "none"}></i> */}
								File Transfer
								{/* {isUploading && <i className="number">{uploadingFiles.length}</i>} */}
							</div>
							<div
								onClick={() => onClick("account")}
								className={current == "account" ? "curr account" : "account"}
								style={{ backgroundImage: "url(" + process.env.PUBLIC_URL + "/img/menu-4.png)" }}>
								Account
							</div>
						</div>
						{account ? (
							<div className="nav-bottom">
								{territoryInfo ? (
									<div>
										{/* {uploadingFiles.length ? (
											<Popconfirm
												placement="right"
												showCancel={false}
												open={openPopconfirm}
												title="The list of uploading is here"
												description="Click to view detailed list"
												okText="OK"
												onConfirm={() => setOpenPopconfirm(false)}>
												<div className="uploading-list" onClick={() => setShowFileListBox(true)}>
													<div className={isUploading ? "bg-icon rotate" : "bg-icon"}></div>
													<div className="icon"></div>
												</div>
											</Popconfirm>
										) : (
											""
										)} */}
										<Progress percent={parseInt((territoryInfo.usedSpaceGib * 100) / territoryInfo.totalSpaceGib)} showInfo={false} />
										<div className="use-per">
											{territoryInfo.remainingSpaceStr?.replace(" ", "")} free of {territoryInfo.totalSpaceStr?.replace(" ", "")}
										</div>
										{
											territoryInfo.state == 'Active' ?
												(<div className="ex">Expire on {territoryInfo.remainingDays}d</div>) :
												(<div className="red">{territoryInfo.state}</div>)
										}

										<div className="btn-link" onClick={() => onClick("territories")}>
											Territories Management
										</div>
										{!isAuth && (
											<div className="btn-link red" onClick={onAuthorize}>
												authorize
											</div>
										)}
									</div>
								) : (
									<div>
										{!isAuth && (
											<div className="btn-link red" onClick={onAuthorize}>
												authorize
											</div>
										)}
										<div className="btn-link" onClick={() => onClick("territories")}>
											Territories Management
										</div>
									</div>
								)}
							</div>
						) : (
							<div className="nav-bottom">
								<Button loading={isloading} disabled={isloading} type="primary" onClick={() => navigate("/login")}>
									Login
								</Button>
							</div>
						)}
					</div>
					<div className="content-side">
						<div className="content-in">
							<Routes>
								<Route path="/" element={<Discover />} />
								<Route path="/discover" element={<Discover />} />
								<Route path="/list/:q" element={<DiscoverList />} />
								<Route path="/territory/:q" element={<TerritoryModify />} />
								<Route path="/territories" element={<TerritoryList />} />
								<Route path="/myfiles" element={<Myfiles />} />
								<Route path="/account" element={<Account />} />
								<Route path="/detail/:fid" element={<FileDetail />} />
								<Route path="/share/:shareid" element={<FileDetail />} />
							</Routes>
						</div>
					</div>
				</div>
			)}
			<Modal
				width={1000}
				open={showFileListBox}
				title={"Uploading Files"}
				footer={[
					<Button key="back" onClick={() => setShowFileListBox(false)}>
						Close
					</Button>
				]}
				onCancel={() => setShowFileListBox(false)}>
				<div className="file-list-box">
					<div className="tab">
						<span className={uploadBoxTab == "uploading" ? "curr" : ""} onClick={() => onUploadTabTurn("uploading")}>Uploading</span>
						<span className={uploadBoxTab == "transferred" ? "curr" : ""} onClick={() => onUploadTabTurn("transferred")}>Transferred</span>
					</div>
					{uploadBoxTab == "uploading" ? uploadingFiles.map(rendUploadList) : transferredFiles.map(rendUploadList)}
					{uploadBoxTab == "uploading" && uploadingFiles.length == 0 ? <Empty /> : ""}
					{uploadBoxTab == "transferred" && transferredFiles.length == 0 ? <Empty /> : ""}
				</div>
			</Modal>
		</div>
	);
}

export default App;
